'''
Author: didiplus
Date: 2022-12-01 14:16:30
LastEditTime: 2022-12-02 11:35:37
LastEditors: didiplus
Description: 
FilePath: //pythonscript//telnetTools.py
Copyright (c)  Didiplus Inc
'''
from telnetlib import Telnet
from loguru import logger
import time
from datetime import datetime


class TelnetClient():
    
    def __init__(self,host,username,password):
        self.tn = Telnet()
        self.host = host
        self.username = username
        self.password = password
    
    def loginHost(self):
        try:
          self.tn.open(self.host,port=23)
        except:
          logger.error("{}网络连接失败".format(self.host))
        # 等待login出现后输入用户名，最多等待10秒  华为交换机登录 Username: 
        self.tn.read_until(b'Username: ',timeout=10)
        self.tn.write(self.username.encode('ascii') + b'\n')
        # 等待Password出现后输入用户名，最多等待10秒
        self.tn.read_until(b'Password',timeout=10)
        self.tn.write(self.password.encode('ascii')+ b'\n')
        # 延时两秒再收取返回结果，给服务端足够响应时间
        time.sleep(2)
        # read_very_eager()获取到的是的是上次获取之后本次获取之前的所有输出
        command_result  = self.tn.read_very_eager().decode('ascii')
        if 'Login incorrect' not in command_result:
            logger.info("{}登录成功".format(self.host))
            return True
        else:
            logger.warning("{}登录失败，用户名或密码错误".format(self.host))
            return False
    
    
    def execute_single_command(self,command:str):
        try:
          self.tn.write(command.encode("ascii")+b"\n")
          time.sleep(2)
          command_result = self.tn.read_very_eager().decode("ascii")
          logger.info("命令执行结果：{}".format(command_result))
          return command_result
        except:
          logger.error("{}:命令执行失败".format(command))
    
    def execute_batch_command(self,commands:list):
        try:
          resultSet=[]
          if isinstance(commands,list):
              for command in commands:
                resultSet.append(self.execute_single_command(command))
              return resultSet
          else:
              logger.warning("{}传递的参数错误，不是一个list列表")
              return False
        except:
          logger.error("命令执行失败")
    
    def save_result(self,data):
        try:
          with open('{}_{}.txt'.format(self.host,datetime.now().strftime("%Y_%m_%d_%H_%M_%S")),mode="w") as f:
              f.write(data)
        except Exception as e:
          logger.error("数据写入失败，原因是{}".format(e))
          print('An exception occurred')
    
    def logout(self):
        self.tn.write(b"exit\n")



    

if __name__ == "__main__":
    telnet = TelnetClient("10.91.74.35","user","pass")
    telnet.loginHost()
    res = telnet.execute_single_command("display version")
    telnet.save_result(res)